
import { toFormField } from '@src/component/form/util';
import * as FormUtil from '@src/component/form/util';
import * as FormUtilValidate from '@src/mform/util/validate';

/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';

// api
import { 
  solutionGetFields, // 获取解决方案表单字段
  solutionSaveFields, // 保存解决方法表单
} from '@src/api/Fault';
import { getProductFieldsV2 } from '@src/api/ProductApi';

import i18n from '@src/locales';
export default {
  name: 'FailureLibrarySetting',

  mixins: [fieldMixin, FormDesignMixin],

  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },

  data(){
    return {
      loading: false,
      fields: [],
      maxField: this.initData.fieldNum,

      productMenuOptions: {
        value: []
      }
    }
  },


  mounted(){
    this.initialize()
  },

  methods: {
    async initialize() {
      this.loading = true;

      const { status, data } = await solutionGetFields();


      this.loading = false; 

      if( status !== 0 ) return

      this.fields = this.toFormField(data || []);
    },

    
    toFormField(fields = []) {
      let sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
      return toFormField(sortedFields);
    },

    // 将字段转换成后端可接收的字段
    packToField(origin) {
      let fields = FormUtil.toField(origin);

      fields.forEach((field, index) => {
        field.orderNum = index;
      });

      return fields;
    },
    
    // 提交表单
    async submit() {
      try {
        let copyFields = [ ...this.fields ]

        copyFields.map(item => {
          if(item.formType === 'subSparePart'){
            item.fieldName = 'subSparePart'
          }
        })

        const allFields = this.packToField(this.fields)
        
        // 表单字段格式校验
        let checkMessage = FormUtil.validate(allFields);
        if (!FormUtilValidate.notification(checkMessage)) return;
        this.loading = true;

        let ret = await solutionSaveFields(allFields);

        const { status, message } = ret;
        if (status !== 0) {
          return this.$message.error(message);
        } 
        this.loading = false;
        this.$message.success(this.$t('common.base.tip.updateSuccess'));
        
        
      } catch (err) {
        console.log('error => submitField', err);
      } finally {
        this.loading = false;
      }
    }

  },
}
